package geoapi

import (
	"encoding/json"
	"errors"
)

// juheResp
type juheResp struct {
	ErrCode    int    `json:"error_code"`
	ResultCode string `json:"resultcode"`
	Reason     string `json:"reason"`
	Result     struct {
		Country  string
		Province string
		City     string
		Isp      string
	} `json:"result"`
}

// GeoJuhe 请求聚合 api 查询ip地址
// https://apis.juhe.cn/ip/Example/query.php?IP=xxx.xxx.xxx.xxx
// host: ip地址
func GeoJuhe(host string) (ig IPGeo, err error) {
	uri := `https://apis.juhe.cn/ip/Example/query.php?IP=` + host
	data, err := getApiData(uri)
	if err != nil {
		return
	}
	var t juheResp
	err = json.Unmarshal(data, &t)
	if err != nil {
		return
	}
	if t.ErrCode != 0 {
		err = errors.New(t.Reason)
		return
	}
	ig.City = t.Result.City
	ig.CountryCode = getCountryCode(t.Result.Country)
	ig.CountryName = t.Result.Country
	ig.Isp = t.Result.Isp
	ig.Query = host
	ig.StateProv = t.Result.Province
	ig.Status = "success"
	return
}
